package com.buba.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSClientBuilder;
import common.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.*;

@RestController
@RequestMapping("/api")
public class UploadController {

    String endpoint = "oss-cn-beijing.aliyuncs.com";
    String keyId = "LTAI5tRH9q1Vn8Arkhcbwa2q";
    String keySecret = "w9cccGdKceT762nGk0C7pOCCwpzZam";
    String bucketName = "edu-2004-0926";

    @PostMapping("/upload")
    public R upload(@RequestBody Map<String, String> data) {
        OSS ossClient = new OSSClientBuilder().build(endpoint, keyId, keySecret);
        String base64 = data.get("base64");
        String[] arr = base64.split(",");
        String type = arr[0].split(";")[0].split("/")[1];
        String fileName = UUID.randomUUID().toString() + "." + type;
        byte[] bytes = Base64.getDecoder().decode(arr[1]);

        try {
            ossClient.putObject("edu-2004-0926", fileName, new ByteArrayInputStream(bytes));
            String url = ossClient.generatePresignedUrl("edu-2004-0926", fileName, new Date(System.currentTimeMillis() + 3600 * 1000)).toString();
            return R.success(url);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error();
        }
    }

    @PostMapping("/uploadFile")
    public List<String>  upload(@RequestParam("file") MultipartFile[] files) throws IOException {
        List<String> list = new ArrayList<>();
        for (MultipartFile file : files) {
            String fileName = file.getOriginalFilename();
            String key = UUID.randomUUID().toString() + "/" + fileName;
            OSS ossClient = new OSSClientBuilder().build(endpoint, keyId, keySecret);
            String url = ossClient.generatePresignedUrl("edu-2004-0926", key, new Date(System.currentTimeMillis() + 3600 * 1000)).toString();
            // 将文件URL保存到数据库中
            list.add(url);
        }
        return list;
    }

    @GetMapping("/delete/{url}")
    public String delete(@PathVariable String url) {
        String key = url.substring(url.lastIndexOf("/") + 1);
        OSS ossClient = new OSSClientBuilder().build(endpoint, keyId, keySecret);
        ossClient.deleteObject("edu-2004-0926", key);
        // 从数据库中删除文件URL
        return "删除成功";
    }
}
